<template>
  <view class="page-container" v-if="order">
    <!-- 顶部导航 -->
    <uni-nav-bar 
      title="订单详情" 
      left-icon="left" 
      :border="false"
      background-color="#fff"
      @clickLeft="handleBack"
    >
      <template #right>
        <uni-icons type="more-filled" size="20" color="#666" @click="showMoreActions"></uni-icons>
      </template>
    </uni-nav-bar>

    <scroll-view scroll-y class="detail-scroll">
      <!-- 订单状态卡片 -->
      <view class="status-card">
        <view class="status-header">
          <uni-tag :text="getOrderStatus(order.status).text" :type="getOrderStatus(order.status).type" size="normal" />
          <text class="order-no">{{ order.order_no }}</text>
        </view>
        <view class="status-amount">
          <text class="amount-label">订单金额</text>
          <text class="amount-value">¥{{ (order.total_amount / 100).toFixed(2) }}</text>
        </view>
      </view>

      <!-- 订单流程时间轴 -->
      <uni-card title="订单流程" :is-shadow="true">
        <view class="timeline">
          <view 
            v-for="(step, index) in orderSteps" 
            :key="index"
            class="timeline-item"
            :class="{ active: step.active, completed: step.completed }"
          >
            <view class="timeline-dot">
              <uni-icons 
                :type="step.completed ? 'checkmarkempty' : 'radio-filled'" 
                :color="step.completed ? '#52c41a' : (step.active ? 'var(--primary-color)' : '#d9d9d9')"
                size="16"
              ></uni-icons>
            </view>
            <view class="timeline-content">
              <text class="timeline-title">{{ step.title }}</text>
              <text v-if="step.time" class="timeline-time">{{ step.time }}</text>
              <text v-if="step.remark" class="timeline-remark">{{ step.remark }}</text>
            </view>
          </view>
        </view>
      </uni-card>

      <!-- 预定信息 -->
      <uni-card title="预定信息" :is-shadow="true">
        <view class="booking-info">
          <view class="info-row">
            <view class="info-item">
              <uni-icons type="location" size="16" color="var(--primary-color)"></uni-icons>
              <view class="info-content">
                <text class="info-label">门店场地</text>
                <text class="info-value">{{ order.store?.name }} - {{ order.venue?.name }}</text>
              </view>
            </view>
          </view>
          <view class="info-row">
            <view class="info-item">
              <uni-icons type="calendar" size="16" color="var(--primary-color)"></uni-icons>
              <view class="info-content">
                <text class="info-label">预定时间</text>
                <text class="info-value">{{ formatTime(order.start_time, 'YYYY-MM-DD HH:mm') }}</text>
                <text class="info-sub">至 {{ formatTime(order.end_time, 'HH:mm') }}</text>
              </view>
            </view>
          </view>
          <view class="info-row">
            <view class="info-item">
              <uni-icons type="person" size="16" color="var(--primary-color)"></uni-icons>
              <view class="info-content">
                <text class="info-label">预定会员</text>
                <text class="info-value">{{ order.member?.name || 'N/A' }}</text>
                <text v-if="order.member?.phone" class="info-sub">{{ order.member.phone }}</text>
              </view>
            </view>
          </view>
        </view>
      </uni-card>

      <!-- 费用明细 -->
      <uni-card title="费用明细" :is-shadow="true">
        <view class="cost-details">
          <view class="cost-item">
            <text class="cost-label">场地费用</text>
            <text class="cost-value">¥{{ (order.total_amount / 100).toFixed(2) }}</text>
          </view>
          <view v-if="order.use_balance" class="cost-item">
            <text class="cost-label">余额支付</text>
            <text class="cost-value balance">-¥{{ (order.balance_amount / 100).toFixed(2) }}</text>
          </view>
          <view class="cost-divider"></view>
          <view class="cost-item total">
            <text class="cost-label">实付金额</text>
            <text class="cost-value">¥{{ (order.pay_amount / 100).toFixed(2) }}</text>
          </view>
          <view class="payment-status">
            <text class="payment-label">支付状态：</text>
            <uni-tag :text="getPaymentStatus(order.payment_status).text" :type="getPaymentStatus(order.payment_status).type" size="small" />
          </view>
        </view>
      </uni-card>

      <!-- 备注信息 -->
      <uni-card v-if="order.remark" title="备注信息" :is-shadow="true">
        <view class="remark-content">
          <text class="remark-text">{{ order.remark }}</text>
        </view>
      </uni-card>

      <!-- 操作历史 -->
      <uni-card v-if="operationHistory.length > 0" title="操作历史" :is-shadow="true">
        <view class="history-list">
          <view v-for="(history, index) in operationHistory" :key="index" class="history-item">
            <view class="history-time">{{ formatTime(history.created_at) }}</view>
            <view class="history-content">
              <text class="history-action">{{ history.action }}</text>
              <text v-if="history.remark" class="history-remark">{{ history.remark }}</text>
              <text class="history-operator">操作人：{{ history.operator || '系统' }}</text>
            </view>
          </view>
        </view>
      </uni-card>
    </scroll-view>

    <!-- 操作按钮 -->
    <view class="action-buttons safe-area-inset-bottom">
      <button v-if="order.status === OrderStatus.Pending" class="action-btn primary" @click="handleUpdateStatus(OrderStatus.Confirmed)">确认订单</button>
      <button v-if="order.status === OrderStatus.Confirmed" class="action-btn primary" @click="handleUpdateStatus(OrderStatus.Completed)">完成订单</button>
      <button v-if="order.status === OrderStatus.Confirmed" class="action-btn default" @click="openReschedulePopup">更换场地</button>
      <button v-if="order.status === OrderStatus.Pending || order.status === OrderStatus.Confirmed" class="action-btn danger" @click="handleUpdateStatus(OrderStatus.Cancelled)">取消订单</button>
    </view>

    <!-- 状态变更备注弹窗 -->
    <uni-popup ref="statusPopup" type="dialog">
      <uni-popup-dialog mode="input" title="确认操作" :placeholder="`请输入备注(可选)`" @confirm="confirmUpdateStatus">
        <template #default>
          <view>确定要将订单状态变更为'{{targetStatusText}}'吗?</view>
        </template>
      </uni-popup-dialog>
    </uni-popup>
    
    <!-- 更换场地弹窗 -->
    <uni-popup ref="reschedulePopup" type="bottom">
      <view class="popup-content safe-area-inset-bottom">
        <view class="popup-header">
          <text class="popup-title">选择新场地</text>
          <uni-icons type="closeempty" size="20" color="#999" @click="reschedulePopup.close()"></uni-icons>
        </view>
        <picker-view :indicator-style="indicatorStyle" :value="selectedVenueIndex" @change="bindVenueChange" class="picker-view">
          <picker-view-column>
            <view v-for="item in venueOptions" :key="item.id" class="picker-item">{{ item.name }}</view>
          </picker-view-column>
        </picker-view>
        <button class="popup-confirm-btn" @click="confirmReschedule">确认更换</button>
      </view>
    </uni-popup>

  </view>
  <view v-else class="loading-container">
    <uni-load-more status="loading"></uni-load-more>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { fetchOrderDetail, updateOrderStatus, rescheduleOrder } from '@/api/order';
import { fetchVenuesByStore } from '@/api/store';
import type { Order, Venue } from '@/types/order';
import { OrderStatus, PaymentStatus } from '@/types/order';
import moment from 'moment';

const order = ref<Order | null>(null);
const statusPopup = ref<any>(null);
const reschedulePopup = ref<any>(null);
const targetStatus = ref<OrderStatus | null>(null);
const targetStatusText = ref('');

const venueOptions = ref<Venue[]>([]);
const selectedVenueIndex = ref([0]);

const indicatorStyle = `height: 50px;`;

// 操作历史数据
const operationHistory = ref<Array<{
  id: number;
  action: string;
  remark?: string;
  operator?: string;
  created_at: number;
}>>([]);

// 订单流程步骤
const orderSteps = computed(() => {
  if (!order.value) return [];
  
  const steps = [
    {
      title: '订单创建',
      completed: true,
      active: false,
      time: formatTime(order.value.created_at),
      remark: '订单已创建'
    },
    {
      title: '等待确认',
      completed: order.value.status >= OrderStatus.Confirmed,
      active: order.value.status === OrderStatus.Pending,
      time: order.value.status >= OrderStatus.Confirmed ? formatTime(order.value.created_at + 3600) : undefined,
      remark: order.value.status >= OrderStatus.Confirmed ? '订单已确认' : '等待管理员确认'
    },
    {
      title: '订单完成',
      completed: order.value.status === OrderStatus.Completed,
      active: order.value.status === OrderStatus.Confirmed,
      time: order.value.status === OrderStatus.Completed ? formatTime(order.value.end_time) : undefined,
      remark: order.value.status === OrderStatus.Completed ? '订单已完成' : '等待完成'
    }
  ];

  // 如果订单被取消，添加取消步骤
  if (order.value.status === OrderStatus.Cancelled) {
    steps.push({
      title: '订单取消',
      completed: true,
      active: false,
      time: formatTime(order.value.created_at + 1800),
      remark: '订单已取消'
    });
  }

  return steps;
});

const getOrderDetail = async (id: number) => {
  try {
    const res = await fetchOrderDetail(id);
    order.value = res;
  } catch (error) {
    console.error('获取订单详情失败:', error);
    uni.showToast({ title: '加载失败', icon: 'none' });
  }
};

const handleUpdateStatus = (status: OrderStatus) => {
  targetStatus.value = status;
  targetStatusText.value = getOrderStatus(status).text;
  statusPopup.value.open();
};

const confirmUpdateStatus = async (remark: string) => {
  if (!targetStatus.value || !order.value) return;
  try {
    await updateOrderStatus(order.value.id, targetStatus.value, remark);
    uni.showToast({ title: '操作成功', icon: 'success' });
    getOrderDetail(order.value.id);
  } catch (error: any) {
    uni.showToast({ title: error.message || '操作失败', icon: 'none' });
  }
};

const openReschedulePopup = async () => {
  if (!order.value?.store_id) return;
  try {
    const res = await fetchVenuesByStore(order.value.store_id);
    venueOptions.value = res.list;
    reschedulePopup.value.open();
  } catch (error) {
    uni.showToast({ title: '获取场地列表失败', icon: 'none' });
  }
};

const bindVenueChange = (e: any) => {
  selectedVenueIndex.value = e.detail.value;
};

const confirmReschedule = async () => {
  if (!order.value) return;
  const newVenueId = venueOptions.value[selectedVenueIndex.value[0]].id;
  if (!newVenueId || newVenueId === order.value.venue_id) {
    uni.showToast({ title: '请选择一个不同的场地', icon: 'none' });
    return;
  }
  try {
    await rescheduleOrder(order.value.id, newVenueId);
    uni.showToast({ title: '更换成功', icon: 'success' });
    reschedulePopup.value.close();
    getOrderDetail(order.value.id);
  } catch (error: any) {
    uni.showToast({ title: error.message || '更换失败', icon: 'none' });
  }
};

const getOrderStatus = (status: OrderStatus) => {
  const map: Record<OrderStatus, { text: string; type: 'success' | 'primary' | 'warning' | 'error' | 'info' }> = {
    [OrderStatus.Pending]: { text: '待处理', type: 'warning' },
    [OrderStatus.Confirmed]: { text: '已确认', type: 'primary' },
    [OrderStatus.Completed]: { text: '已完成', type: 'success' },
    [OrderStatus.Cancelled]: { text: '已取消', type: 'error' },
    [OrderStatus.Rescheduled]: { text: '已改签', type: 'info' },
  };
  return map[status] || { text: '未知', type: 'info' };
};

const getPaymentStatus = (status: PaymentStatus) => {
  const map: Record<PaymentStatus, { text: string; type: 'success' | 'warning' | 'error' }> = {
    [PaymentStatus.Unpaid]: { text: '未支付', type: 'warning' },
    [PaymentStatus.Paid]: { text: '已支付', type: 'success' },
    [PaymentStatus.Refunded]: { text: '已退款', type: 'error' },
  };
  return map[status] || { text: '未知', type: 'warning' };
};

const formatTime = (timestamp: number, format = 'YYYY-MM-DD HH:mm') => {
  return moment(timestamp * 1000).format(format);
};

// 返回上一页
const handleBack = () => {
  uni.navigateBack();
};

// 显示更多操作
const showMoreActions = () => {
  const actions = ['分享订单', '导出订单', '联系客服'];
  uni.showActionSheet({
    itemList: actions,
    success: (res) => {
      switch (res.tapIndex) {
        case 0:
          // 分享订单
          shareOrder();
          break;
        case 1:
          // 导出订单
          exportOrder();
          break;
        case 2:
          // 联系客服
          contactService();
          break;
      }
    }
  });
};

// 分享订单
const shareOrder = () => {
  if (!order.value) return;
  uni.share({
    provider: 'weixin',
    scene: 'WXSceneSession',
    type: 0,
    href: `订单详情：${order.value.order_no}`,
    title: '订单分享',
    summary: `订单金额：¥${(order.value.total_amount / 100).toFixed(2)}`,
    success: () => {
      uni.showToast({ title: '分享成功', icon: 'success' });
    }
  });
};

// 导出订单
const exportOrder = () => {
  uni.showToast({ title: '导出功能开发中', icon: 'none' });
};

// 联系客服
const contactService = () => {
  uni.makePhoneCall({
    phoneNumber: '400-123-4567'
  });
};

onLoad((options: any) => {
  if (options.id) {
    getOrderDetail(Number(options.id));
  }
});
</script>

<style lang="scss" scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.detail-scroll {
  flex: 1;
  height: 0;
  padding-bottom: 80px;
}

.uni-card {
  margin: 10px !important;
  border-radius: 8px !important;
}

// 订单状态卡片
.status-card {
  background: linear-gradient(135deg, #007AFF 0%, #5AC8FA 100%);
  margin: 10px;
  padding: 20px;
  border-radius: 12px;
  color: #fff;

  .status-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;

    .order-no {
      font-size: 14px;
      opacity: 0.9;
    }
  }

  .status-amount {
    .amount-label {
      font-size: 12px;
      opacity: 0.8;
      display: block;
      margin-bottom: 5px;
    }

    .amount-value {
      font-size: 24px;
      font-weight: bold;
    }
  }
}

// 时间轴样式
.timeline {
  .timeline-item {
    display: flex;
    padding: 15px 0;
    position: relative;

    &:not(:last-child)::after {
      content: '';
      position: absolute;
      left: 7px;
      top: 35px;
      bottom: -15px;
      width: 2px;
      background-color: #e8e8e8;
    }

    &.completed::after {
      background-color: #52c41a;
    }

    .timeline-dot {
      width: 16px;
      height: 16px;
      margin-right: 15px;
      flex-shrink: 0;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .timeline-content {
      flex: 1;

      .timeline-title {
        font-size: 14px;
        font-weight: 500;
        color: #333;
        display: block;
        margin-bottom: 4px;
      }

      .timeline-time {
        font-size: 12px;
        color: #666;
        display: block;
        margin-bottom: 2px;
      }

      .timeline-remark {
        font-size: 12px;
        color: #999;
        display: block;
      }
    }

    &.active .timeline-content .timeline-title {
      color: #007AFF;
      font-weight: 600;
    }

    &.completed .timeline-content .timeline-title {
      color: #52c41a;
    }
  }
}

// 预定信息样式
.booking-info {
  .info-row {
    margin-bottom: 15px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .info-item {
    display: flex;
    align-items: flex-start;
    gap: 10px;

    .info-content {
      flex: 1;

      .info-label {
        font-size: 12px;
        color: #666;
        display: block;
        margin-bottom: 4px;
      }

      .info-value {
        font-size: 14px;
        color: #333;
        font-weight: 500;
        display: block;
        margin-bottom: 2px;
      }

      .info-sub {
        font-size: 12px;
        color: #999;
        display: block;
      }
    }
  }
}

// 费用明细样式
.cost-details {
  .cost-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    font-size: 14px;

    .cost-label {
      color: #666;
    }

    .cost-value {
      color: #333;
      font-weight: 500;

      &.balance {
        color: #52c41a;
      }
    }

    &.total {
      border-top: 1px solid #f0f0f0;
      padding-top: 12px;
      margin-top: 8px;

      .cost-label {
        font-weight: 600;
        color: #333;
      }

      .cost-value {
        font-size: 16px;
        font-weight: 600;
        color: #ff4d4f;
      }
    }
  }

  .cost-divider {
    height: 1px;
    background-color: #f0f0f0;
    margin: 8px 0;
  }

  .payment-status {
    display: flex;
    align-items: center;
    margin-top: 12px;
    padding-top: 12px;
    border-top: 1px solid #f0f0f0;

    .payment-label {
      font-size: 12px;
      color: #666;
      margin-right: 8px;
    }
  }
}

// 备注信息样式
.remark-content {
  .remark-text {
    font-size: 14px;
    color: #666;
    line-height: 1.6;
    background-color: #f8f9fa;
    padding: 12px;
    border-radius: 6px;
    border-left: 3px solid #007AFF;
  }
}

// 操作历史样式
.history-list {
  .history-item {
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .history-time {
      font-size: 12px;
      color: #999;
      margin-bottom: 4px;
    }

    .history-content {
      .history-action {
        font-size: 14px;
        color: #333;
        font-weight: 500;
        display: block;
        margin-bottom: 2px;
      }

      .history-remark {
        font-size: 12px;
        color: #666;
        display: block;
        margin-bottom: 2px;
      }

      .history-operator {
        font-size: 12px;
        color: #999;
        display: block;
      }
    }
  }
}

// 操作按钮样式
.action-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 12px;
  display: flex;
  gap: 10px;
  border-top: 1px solid #eee;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.1);

  .action-btn {
    flex: 1;
    margin: 0;
    border-radius: 6px;
    font-size: 14px;
    height: 44px;
    
    &.primary {
      background-color: #007AFF;
      color: #fff;
      border: none;
    }
    
    &.default {
      background-color: #f8f9fa;
      color: #333;
      border: 1px solid #d9d9d9;
    }
    
    &.danger {
      background-color: #ff4d4f;
      color: #fff;
      border: none;
    }
  }
}

// 弹窗样式
.popup-content {
  background-color: #fff;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
  padding: 20px;

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .popup-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }
  }

  .picker-view {
    width: 100%;
    height: 200px;
    border: 1px solid #f0f0f0;
    border-radius: 6px;

    .picker-item {
      line-height: 50px;
      text-align: center;
      font-size: 14px;
      color: #333;
    }
  }

  .popup-confirm-btn {
    margin-top: 20px;
    background-color: #007AFF;
    color: #fff;
    border-radius: 6px;
    height: 44px;
    font-size: 16px;
    border: none;
  }
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

// 安全区域适配
.safe-area-inset-bottom {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}
</style>
